package com.moleq.dialog;

import java.util.List;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.moleq.base.MoleQBaseDialog;
import com.moleq.base.OnResultListener;
import com.moleq.device.DeviceManager;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.logic.MoleQConstants;
import com.moleq.logic.TransactionManager;
import com.moleq.models.GlobalInfo;
import com.moleq.models.ItemSetting;
import com.moleq.models.MixMatch;
import com.moleq.models.PriceSetting;
import com.moleq.models.Product;
import com.moleq.models.SubDepartmant;
import com.moleq.mgpos.activities.R;
import com.moleq.service.PriceService;
import com.moleq.service.ProductService;
import com.moleq.service.ServiceManager;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;

public class GlobalPriceChangeDialog2 extends Dialog implements OnResultListener {

	private Button mButtonBack,mButtonOk,mButtonDept,mButtonType;
	private EditText mEditTextValue1,mEditTextValue2;
	private TransactionManager mPaymentMgr;
	private LinearLayout llGPCLabelRate;
	private Context mContext;
	private DeviceManager mDeviceManager; //contral device scanner or scale
	private int selectedRow = 0;
	private int count = 0;
	private String mPriceChangeType;
//	private String dep_no;
	private SubDepartmant mDept;
	private static final int GUI_STOP_NOTIFIER = 0;
	private static final int GUI_THREADING_NOTIFIER = 1;
	private static final int GUI_ENABLE_CONTROLS = 2;
	private static final int GUI_DISABLE_CONTROLS = 3;
	private List<String> upclst;
	private ProgressBar pb_loading;
	private GPCDeptSelectionDialog mPriceDeptSelectionDialog;
	private GPCTypeSelectionDialog mPriceTypeSelectionDialog;
	private TextView tvGPCPercent1,tvProcePer;
	private MGCreateFiles mMGCreateFiles = new MGCreateFiles();
	double a,b;
	int i;
	Handler MessageHandler = new Handler() {
		public void handleMessage(Message message) {
			switch (message.what) {
			case GUI_STOP_NOTIFIER:
				Toast.makeText(mContext, "Save completed. " + count + " Item(s) have been processed.",Toast.LENGTH_SHORT).show();
				Thread.currentThread().interrupt();
				a = pb_loading.getProgress();
				b = upclst.size();
				i = (int) (a / b * 100);
				tvProcePer.setText(i+"%");
				setEnableControl(true);
				count = 0;
				break;
			case GUI_THREADING_NOTIFIER:

				if (!Thread.currentThread().isInterrupted()) {
					a = pb_loading.getProgress();
					b = upclst.size();
					i = (int) (a / b * 100);
					tvProcePer.setText(i+"%");
					pb_loading.setVisibility(View.VISIBLE);
				}
				break;
				
			case GUI_DISABLE_CONTROLS:
				setEnableControl(false);
				break;
			case GUI_ENABLE_CONTROLS:
				setEnableControl(true);
				break;
			
			}
		}
	};
	
	
	private Button.OnClickListener mOnClickListener = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {	
			switch(v.getId()){
			case R.id.btnPriceChangeCancel:
				InputMethodManager inputMethodManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
				inputMethodManager.hideSoftInputFromWindow(GlobalPriceChangeDialog2.this
						.getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
				mDeviceManager.enableAllScanner();
				dismiss();
				break;
			case R.id.btnPriceChangeOk:	
				
				if (validation()) {
					MessageBox.show(mContext, "Do you want to preform a global price change now?",onClickMessageListener,MessageDialog.MESSAGE_BOX_YES_NO);
				}
				
				break;
			case R.id.btn_dept:
				if(mPriceDeptSelectionDialog == null || mPriceDeptSelectionDialog.isShowing()) return;
				
				mPriceDeptSelectionDialog.show();
				break;
			case R.id.btn_type:
				
				if(mPriceTypeSelectionDialog == null || mPriceTypeSelectionDialog.isShowing()) return;
				
				mPriceTypeSelectionDialog.show();
				break;

			}
		}
	};
	private TextView mAmtLabel;

	
	public void setEnableControl(boolean enabled){
		
		mButtonOk.setEnabled(enabled);
		mButtonBack.setEnabled(enabled);
		mButtonDept.setEnabled(enabled);
		mButtonType.setEnabled(enabled);
		mEditTextValue1.setEnabled(enabled);
		mEditTextValue2.setEnabled(enabled);
	}

	public void Process(List<String> upclst, int i) {
	
		if ((i+1) >= upclst.size()) {
			Message message = new Message();
			message.what = GUI_STOP_NOTIFIER;
			MessageHandler.sendMessage(message);
		} else {
			Message message = new Message();
			message.what = GUI_THREADING_NOTIFIER;
			MessageHandler.sendMessage(message);
		}
		
	}
	
	
	@Override
	public void onReturnValue(int what,Object obj) {
		// TODO Auto-generated method stub
		
		switch(what){
		case MoleQConstants.DIALOG_PRICE_DEPT_INFO:
			mDept = (SubDepartmant)obj;
			mButtonDept.setText(mDept.getSd_name());
			break;
		case MoleQConstants.DIALOG_PRICE_TYPE_INFO:
			mPriceChangeType = obj.toString();
			mButtonType.setText(String.valueOf(mPriceChangeType));
			mAmtLabel.setText("Amount");
			llGPCLabelRate.setVisibility(View.INVISIBLE);
			
			if (mButtonType.getText().equals(MoleQConstants.GPC_DISCOUNT)) {
				llGPCLabelRate.setVisibility(View.VISIBLE);
				mAmtLabel.setVisibility(View.VISIBLE);
				tvGPCPercent1.setVisibility(View.INVISIBLE);
			} else if (mButtonType.getText().equals(MoleQConstants.GPC_INCREASE_PRICE_BY_PER)
					|| mButtonType.getText().equals(MoleQConstants.GPC_DECREASE_PRICE_BY_PER)) {
				tvGPCPercent1.setVisibility(View.VISIBLE);
				mAmtLabel.setVisibility(View.INVISIBLE);
			} else if (mButtonType.getText().equals(MoleQConstants.GPC_DECREASE_AMOUNT)
					|| mButtonType.getText().equals(MoleQConstants.GPC_INCREASE_AMOUNT)) {
				tvGPCPercent1.setVisibility(View.INVISIBLE);
				mAmtLabel.setVisibility(View.VISIBLE);
			} else if (mButtonType.getText().toString().equals(MoleQConstants.GPC_REPLACE_THE_PRICE)) {
				tvGPCPercent1.setVisibility(View.INVISIBLE);
				mAmtLabel.setText("To Be");
				mAmtLabel.setVisibility(View.VISIBLE);
			}
			break;
		}
		
	}
	
	public GlobalPriceChangeDialog2(Context context) {
		super(context,R.style.dialog2);
		constructor(context);
		
	}

	public GlobalPriceChangeDialog2(Context context, int theme) {
		super(context, theme);
		constructor(context);
	}
	
	private void constructor(Context context) {
		// TODO Auto-generated method stub
		mContext = context;
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set UI layout
		this.setContentView(R.layout.dialog_price_global_price_change);
		this.setCancelable(false);
	
		mButtonBack = (Button) findViewById(R.id.btnPriceChangeCancel);
		mButtonBack.setOnClickListener(mOnClickListener);
		
		mButtonOk = (Button) findViewById(R.id.btnPriceChangeOk);
		mButtonOk.setOnClickListener(mOnClickListener);
		
		mButtonDept = (Button) findViewById(R.id.btn_dept);
		mButtonDept.setOnClickListener(mOnClickListener);
		
		mButtonType = (Button) findViewById(R.id.btn_type);
		mButtonType.setOnClickListener(mOnClickListener);
		
		mEditTextValue1 = (EditText) findViewById(R.id.etPriceChangeValue1);
		mEditTextValue2 = (EditText) findViewById(R.id.etPriceChangeValue2);
		
		mAmtLabel = (TextView)this.findViewById(R.id.tvGPCLabelAmt);
		tvGPCPercent1 = (TextView)this.findViewById(R.id.tvGPCPercent1);
		
		pb_loading = (ProgressBar) this.findViewById(R.id.pb_loading);
		tvProcePer = (TextView) this.findViewById(R.id.tvProcePer);
		pb_loading.setIndeterminate(false);
		
		llGPCLabelRate = (LinearLayout)this.findViewById(R.id.llGPCLabelRate);
	}
	
	public boolean validation(){
		boolean result = true;		
		
		if (mButtonDept.getText().toString().equals("")) {
			MessageBox.show(mContext, "Please select department.");
			result = false;
		}
		
		if ((mPriceChangeType.equals(MoleQConstants.GPC_INCREASE_AMOUNT)|| mPriceChangeType.equals(MoleQConstants.GPC_DECREASE_AMOUNT)) 
				&& mEditTextValue1.getText().toString().equals("")) {
			MessageBox.show(mContext, "Amount cannot be empty.");
			mEditTextValue1.requestFocusFromTouch();
			result = false;
		}
		
		if ((mPriceChangeType.equals(MoleQConstants.GPC_INCREASE_PRICE_BY_PER) 
				|| mPriceChangeType.equals(MoleQConstants.GPC_DECREASE_PRICE_BY_PER)) 
				&& mEditTextValue1.getText().toString().equals("")) {
			MessageBox.show(mContext, "Percent cannot be empty.");
			mEditTextValue1.requestFocusFromTouch();
			result = false;
		}
		
		if ((mPriceChangeType.equals(MoleQConstants.GPC_INCREASE_PRICE_BY_PER) 
				|| mPriceChangeType.equals(MoleQConstants.GPC_DECREASE_PRICE_BY_PER)) 
				&&  Double.valueOf(mEditTextValue1.getText().toString()) > 100) {
			MessageBox.show(mContext, "Cannot be more than 100%.");
			mEditTextValue1.requestFocusFromTouch();
			result = false;
		}
		
		double result1 = MoleQUtil.fixPointToString(mEditTextValue1.getText().toString());
		if(!mPriceChangeType.equals(MoleQConstants.GPC_DISCOUNT) && result1 == 0){
			MessageBox.show(mContext, "Please enter a valid number.");
			mEditTextValue1.requestFocusFromTouch();
			result = false;
		}
		
		if (mPriceChangeType.equals(MoleQConstants.GPC_DISCOUNT)  && mEditTextValue1.getText().toString().equals("") &&
				mEditTextValue2.getText().toString().equals("")) {
			MessageBox.show(mContext, "Amount and Rate cannot be empty.");
			mEditTextValue1.requestFocusFromTouch();
			result = false;
		}
		return result;
	}
	
	public void show(){
		super.show();		
		
		mPriceDeptSelectionDialog = new GPCDeptSelectionDialog(mContext,this);
		mPriceTypeSelectionDialog = new GPCTypeSelectionDialog(mContext,this);
		
		mDeviceManager = DeviceManager.getInstance();
		mPaymentMgr =  TransactionManager.getInstance();
		mDeviceManager.disableAllScanner();
		
		mPriceChangeType = MoleQConstants.GPC_INCREASE_PRICE_BY_PER;
		mButtonType.setText(mPriceChangeType);
	}
	
	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		@Override
		public void onClickYes() {
			// TODO Auto-generated method stub
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
//					enablebtn(false);

					Message message = new Message();
					message.what = GUI_DISABLE_CONTROLS;
					MessageHandler.sendMessage(message);
							
						String strP4 = mEditTextValue1.getText().toString();
						double inputPrice = BigDecmialTool.round(MoleQUtil.fixPointToString(strP4), 2);
						
						ProductService svr = ServiceManager.getInstance().mProductService;
						PriceService priceService = ServiceManager.getInstance().mPriceService;
						upclst = svr.getDeptItems2(mDept.getSd_id());
						pb_loading.setMax(upclst.size());
						pb_loading.setProgress(0);
						
						if(mPriceChangeType.equals(MoleQConstants.GPC_INCREASE_PRICE_BY_PER)){
							for (int i = 0; i < upclst.size(); i++) {
								pb_loading.incrementProgressBy(1);
								Product item = svr.Find(upclst.get(i));
								double p4 = item.getPrice();
//								double per = Double.valueOf(mEditTextValue1.getText().toString());
								double rp4 = p4 * (1 + BigDecmialTool.div(inputPrice, 100));
								item.setPrice(BigDecmialTool.round(rp4, 2));
								svr.UpdatePrice(item);
								count++;
								Process(upclst, i);
							}
							if (GlobalInfo.getInstance().isMGNetwork) {
								mMGCreateFiles.createrFile(new ItemSetting().toMGData("GLOBALPRICE","F30*"+(1+BigDecmialTool.div(inputPrice, 100)),mDept.getSd_id()));//UPDATE,DELETE
							}
						}else if(mPriceChangeType.equals(MoleQConstants.GPC_DECREASE_PRICE_BY_PER)){
							for (int i = 0; i < upclst.size(); i++) {
								pb_loading.incrementProgressBy(1);
								Product item = svr.Find(upclst.get(i));
								double p4 = item.getPrice();
//								double per =  Double.valueOf(mEditTextValue1.getText().toString());
								double rp4 = p4 * (1 - BigDecmialTool.div(inputPrice, 100));
								if (rp4 < 0) {
									item.setPrice(BigDecmialTool.round(p4, 2));
								} else {
									item.setPrice(BigDecmialTool.round(rp4, 2));
								}
								svr.UpdatePrice(item);
								count++;
								Process(upclst, i);
							}
							if (GlobalInfo.getInstance().isMGNetwork) {
								mMGCreateFiles.createrFile(new ItemSetting().toMGData("GLOBALPRICE","F30*"+(1 - BigDecmialTool.div(inputPrice, 100)),mDept.getSd_id()));//UPDATE,DELETE
							}
						}else if(mPriceChangeType.equals(MoleQConstants.GPC_INCREASE_AMOUNT)){
							for (int i = 0; i < upclst.size(); i++) {
								pb_loading.incrementProgressBy(1);
								Product item = svr.Find(upclst.get(i));
								double p4 = item.getPrice();
//								double np4 = Double.valueOf(mEditTextValue1.getText().toString());
								item.setPrice(BigDecmialTool.add(p4, inputPrice));
								svr.UpdatePrice(item);
								count++;
								Process(upclst, i);
							}
							if (GlobalInfo.getInstance().isMGNetwork) {
								mMGCreateFiles.createrFile(new ItemSetting().toMGData("GLOBALPRICE","F30 + "+inputPrice,mDept.getSd_id()));//UPDATE,DELETE
							}
						}else if(mPriceChangeType.equals(MoleQConstants.GPC_DECREASE_AMOUNT)){
							for (int i = 0; i < upclst.size(); i++) {
								pb_loading.incrementProgressBy(1);
								Product item = svr.Find(upclst.get(i));
								double p4 = item.getPrice();
//								double np4 = Double.valueOf(mEditTextValue1.getText().toString());
								if (p4 > inputPrice) {
									item.setPrice(BigDecmialTool.sub(p4, inputPrice));
									svr.UpdatePrice(item);
								}
								count++;
								Process(upclst, i);
							}
							if (GlobalInfo.getInstance().isMGNetwork) {
								mMGCreateFiles.createrFile(new ItemSetting().toMGData("GLOBALPRICE","F30 - "+inputPrice,mDept.getSd_id()));//UPDATE,DELETE
							}
						}else if(mPriceChangeType.equals(MoleQConstants.GPC_REPLACE_THE_PRICE)){
							for (int i = 0; i < upclst.size(); i++) {
								pb_loading.incrementProgressBy(1);
								Product item = svr.Find(upclst.get(i));
//								double np4 = Double.valueOf(mEditTextValue1.getText().toString());
								item.setPrice(inputPrice);
								svr.UpdatePrice(item);
								count++;
								Process(upclst, i);
							}
							if (GlobalInfo.getInstance().isMGNetwork) {
								mMGCreateFiles.createrFile(new ItemSetting().toMGData("GLOBALPRICE",String.valueOf(inputPrice),mDept.getSd_id()));//UPDATE,DELETE
							}

						}else if(mPriceChangeType.equals(MoleQConstants.GPC_DISCOUNT)){
							PriceSetting pricesetting = null;
							for (int i = 0; i < upclst.size(); i++) {
								pb_loading.incrementProgressBy(1);
								Product item = svr.Find(upclst.get(i));
								PriceSetting priceSettingObj = new PriceSetting();
//								double np4 = Double.valueOf(mEditTextValue1.getText().toString());
								double Discount = BigDecmialTool.round(MoleQUtil.fixPointToString(mEditTextValue2.getText().toString()), 2);
								//Double.valueOf(mEditTextValue2.getText().toString());
								priceSettingObj.setDiscountamount((inputPrice == 0)?null:String.valueOf(BigDecmialTool.round(inputPrice, 2)));
								priceSettingObj.setDiscountpercent((Discount == 0)?null:String.valueOf(BigDecmialTool.round(Discount, 2)));
								priceSettingObj.setUpc(item.getBarcode());
								priceService.InsertOrUpdatePrice(priceSettingObj);
								if (GlobalInfo.getInstance().isMGNetwork) {
									pricesetting = priceService.getitempricesetting(item.getBarcode());
									mMGCreateFiles.createrFile(pricesetting.toMGData("INSERT"));//UPDATE,DELETE
								}
								count++;
								Process(upclst, i);
							}
						}
					
					
//					enablebtn(true);
					 message = new Message();
					message.what = GUI_ENABLE_CONTROLS;
					MessageHandler.sendMessage(message);
				}
			}).start();
			
		}

		@Override
		public void onClickNo() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onClickOK() {
			// TODO Auto-generated method stub
			
		}

	};


	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass,
			int viewId, String returnvalue) {
		// TODO Auto-generated method stub
		
	}

	

	@Override
	public void onShowingMessageDlg(boolean isShowing) {
		// TODO Auto-generated method stub
		
	}

	
}
